/* -----------------
* brief
* 1. this is code gen by tools
* 2. for add/update/delete/query the data save in sql database
 */

package sysOrders

import (
	"fmt"
	"github.com/go-xorm/xorm"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	"saas_sys_base/common"
	//"github.com/mjiulee/lego/utils"
)

//定义隔离字段
var dbFilterField = []common.WhoFieldType{common.Field_MiniAppId}

/* 根据id获取记录
 * -----------------
 */
func (t *SysOrders) RecodeById(id int64) *SysOrders {
	item := new(SysOrders)
	_, err := lego.GetDBEngine().ID(id).Where("if_del = ?", 0).Get(item)
	if item.Id <= 0 || err != nil {
		return nil
	}
	return item
}

func (t *SysOrders) RecodeByIdWithWho(who *common.Who, id int64) *SysOrders {
	item := new(SysOrders)
	_, err := who.GetFilter(dbFilterField...).ID(id).Get(item)
	if item.Id <= 0 || err != nil {
		return nil
	}
	return item
}

func (t *SysOrders) RecodeByWho(who *common.Who,id int64) *SysOrders {
	item := new(SysOrders)
	_, err := lego.GetDBEngine().ID(id).Where("if_del = ?", 0).And("uid = ?",who.Uid).Get(item)
	if item.Id <= 0 || err != nil {
		return nil
	}
	return item
}

/* 添加
 * -----------------
 */
func (t *SysOrders) AddRecode(item2add *SysOrders) bool {
	item2add.Id = lego.UUID()
	item2add.OrderCode = utils.Int64ToString(item2add.Id)
	_, err := lego.GetDBEngine().Insert(item2add)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

func (t *SysOrders) AddRecodeWithsession(session *xorm.Session, item2add *SysOrders) bool {
	item2add.Id = lego.UUID()
	item2add.OrderCode = utils.Int64ToString(item2add.Id)
	_, err := session.Insert(item2add)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 删除(硬删除)*/
func (t *SysOrders) DelRecodeById(id int64) bool {
	item := new(SysOrders)
	_, err := lego.GetDBEngine().ID(id).Delete(item)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

func (t *SysOrders) DelRecodeByIdWithSession(session *xorm.Session, id int64) bool {
	item := new(SysOrders)
	_, err := session.ID(id).Delete(item)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 更新
 * -----------------*/
func (t *SysOrders) UpdateRecode(rc *SysOrders) bool {
	_, err := lego.GetDBEngine().Id(rc.Id).Omit("id", "if_del").Update(rc)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

func (t *SysOrders) UpdateRecodeWithSession(session *xorm.Session, rc *SysOrders) bool {
	_, err := session.ID(rc.Id).Omit("id", "if_del").Update(rc)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/*查询表名, 注意，函数名不能定义未TableName()，因为会与xorm内部使用的TableName冲突*/
func (t *SysOrders) TName() string {
	tname := lego.GetDBEngine().TableName(t)
	return tname
}

func (t *SysOrders) ListSysOrdersByWho(who *common.Who, orderCode, userName, mobile, beginTime, endTime, productName string, orderType int, shopids []int64, page, psize int, orderField, order string, SysOrderstatus int) ([]*SysOrders, int64, error) {

	start := ((page-1) * psize)
	resultList := make([]*SysOrders, 0)
    start = start
	session := lego.GetDBEngine().Table(SysOrders{}).Alias("t1").
		//Select("t1.*").//,t2.shop_name").
		//Join("inner", []string{"tb_e_shop", "t2"}, "t2.id = t1.e_shop_id").
		Where("t1.if_del = ?", 0)
		//In("t2.e_shop_id", shopids)

	switch SysOrderstatus {
	case UnPayOrder:
		session = session.Where("t1.if_pay = ?", common.STATE_NO)
	case PayOrderWaitDelivery:
		session = session.Where("t1.if_pay = ?", common.STATE_YES).And("t1.if_delivery = ?", common.STATE_NO)
	case SendedOrder:
		session = session.Where("t1.if_delivery = ?", common.STATE_YES).And("t1.if_finish = ?", common.STATE_NO).Where("t1.if_cancel = ?", common.STATE_NO)
	case FinishOrder:
		session = session.Where("t1.if_finish = ?", common.STATE_YES)
	case CancelOrder:
		session = session.Where("t1.if_cancel = ?", common.STATE_YES)
	case RefundOrder:
		session = session.Where("t1.if_refund = ? or t1.if_refund = ?", Refunding, AgreeRefund)
	}

	if len(orderCode) > 0 {
		orderCode = "%" + orderCode + "%"
		session = session.Where("t1.order_code like ?", orderCode)
	}

	if len(userName) > 0 {
		userName = "%" + userName + "%"
		session = session.Where("t1.user_name like ?", userName)
	}

	if len(mobile) > 0 {
		mobile = "%" + mobile + "%"
		session = session.Where("t1.mobile like ?", mobile)
	}

	if len(beginTime) > 0 {
		session = session.Where("t1.cdate >= ?", beginTime)
	}

	if len(endTime) > 0 {
		session = session.Where("t1.cdate <= ?", endTime)
	}

	if len(productName) > 0 {
		productName = "%" + productName + "%"
		session = session.Where("exists (select 1 from tb_sys_order_detail detail where detail.order_id = t1.id and detail.product_name like ?)", productName)
	}

	if orderType > 0 {
		session = session.Where("t1.order_type = ?", orderType)
	}

	if orderField != "" && order != "" {
		SysOrderstr := fmt.Sprintf("t1.%s %s", orderField, order)
		session = session.OrderBy(SysOrderstr)
	} else {
		session = session.OrderBy("t1.cdate desc")
	}

	session2 := session.Clone()

	//Desc("t1.cdate")
	//Asc()
	//OrderBy("asc")
//Limit(psize, start).
	err := session.Limit(psize, start).Select("t1.*").Find(&resultList)
	if err != nil {
		return nil, 0, err
	}

	total, err := session2.Count()
	if err != nil {
		return nil, 0, err
	}
	return resultList, total, err
}

func (t *SysOrders) ListSysOrdersByWhoForMall(who *common.Who, orderCode string, orderType int, shopid int64, page, psize int, orderField, order string, SysOrderstatus int) ([]*SysOrders, int64, error) {

	start := (page * psize)
	resultList := make([]*SysOrders, 0)

	session := lego.GetDBEngine().Table(SysOrders{}).Alias("t1").
		Select("t1.*").
		Where("t1.if_del = ?", 0).
		And("t1.shop_id = ?", shopid).
		And("t1.uid = ?", who.Uid)

	switch SysOrderstatus {
	case UnPayOrder:
		session = session.Where("t1.if_pay = ?", common.STATE_NO)
	case PayOrderWaitDelivery:
		session = session.Where("t1.if_pay = ?", common.STATE_YES).And("t1.if_delivery = ?", common.STATE_NO)
	case SendedOrder:
		session = session.Where("t1.if_delivery = ?", common.STATE_YES).And("t1.if_finish = ?", common.STATE_NO).Where("t1.if_cancel = ?", common.STATE_NO)
	case FinishOrder:
		session = session.Where("t1.if_finish = ?", common.STATE_YES)
	case CancelOrder:
		session = session.Where("t1.if_cancel = ?", common.STATE_YES)
	case RefundOrder:
		session = session.Where("t1.if_refund = ? or t1.if_refund = ?", Refunding, AgreeRefund)
	}

	if len(orderCode) > 0 {
		orderCode = "%" + orderCode + "%"
		session = session.Where("t1.order_code like ?", orderCode)
	}

	if orderType > 0 {
		session = session.Where("t1.order_type = ?", orderType)
	}

	if orderField != "" && order != "" {
		SysOrderstr := fmt.Sprintf("t1.%s %s", orderField, order)
		session = session.OrderBy(SysOrderstr)
	} else {
		session = session.OrderBy("t1.cdate desc")
	}

	session2 := *session.Clone()


	//Desc("t1.cdate")
	//Asc()
	//OrderBy("asc")

	err := session.Limit(psize, start).Find(&resultList)
	if err != nil {
		return nil, 0, err
	}

	total, err := session2.Count()
	if err != nil {
		return nil, 0, err
	}
	return resultList, total, err
}
